import { useCallback, useEffect, useRef, useState } from 'react';

type IceState = RTCPeerConnection['iceConnectionState'];

interface Options {
    onStateChange?: (state: IceState) => void;
    onDisconnected?: () => void;
    onFailed?: () => void;
    autoRestart?: boolean;
}

export function useIceConnectionMonitor(
    pc: RTCPeerConnection | null,
    options?: Options
) {
    const [iceState, setIceState] = useState<IceState>('new');

    useEffect(() => {
        if (!pc) return;

        const handleStateChange = () => {
            const state = pc.iceConnectionState;
            console.log('ICE connection state changed:', state);
            setIceState(state);
            options?.onStateChange?.(state);

            if (state === 'disconnected') {
                options?.onDisconnected?.();
                if (options?.autoRestart) {
                    restartIce(pc);
                }
            }

            if (state === 'failed') {
                options?.onFailed?.();
                if (options?.autoRestart) {
                    restartIce(pc);
                }
            }
        };

        pc.addEventListener('iceconnectionstatechange', handleStateChange);

        return () => {
            pc.removeEventListener('iceconnectionstatechange', handleStateChange);
        };
    }, [pc]);

    return { iceState };
}

// 主动触发 ICE 重启
async function restartIce(pc: RTCPeerConnection) {
    try {
        const offer = await pc.createOffer({ iceRestart: true });
        await pc.setLocalDescription(offer);
        console.log('🔄 ICE 重启已触发');
    } catch (err) {
        console.error('❌ ICE 重启失败:', err);
    }
}



interface UseRTCDataChannelOptions {
    pc: RTCPeerConnection | null; // 已经创建好的 RTCPeerConnection
    label?: string;        // DataChannel 名称
    options?: RTCDataChannelInit; // DataChannel 配置
    onMessage?: (msg: string | ArrayBuffer | Blob) => void;
}

export function useRTCDataChannel({
    pc,
    label = "data",
    options,
    onMessage
}: UseRTCDataChannelOptions) {
    const channelRef = useRef<RTCDataChannel | null>(null);
    const [isOpen, setIsOpen] = useState(false);

    // 发送消息
    const sendMessage = useCallback((data: string | Blob | ArrayBuffer) => {
        const channel = channelRef.current;
        console.log("readyState", channel?.readyState);
        if (channel && channel.readyState === 'open') {
            if (typeof data === 'string' || data instanceof Blob || data instanceof ArrayBuffer) {
                //@ts-ignore
                channel.send(data);
            } else {
                console.warn('Unsupported data type for DataChannel');
            }
        } else {
            console.warn('DataChannel is not open');
        }
    }, []);

    useEffect(() => {
        let channel: RTCDataChannel;
        if (!pc)
            return;
        pc.oniceconnectionstatechange = () => {
            if (pc.iceConnectionState === "connected") {
                if (pc.signalingState === "stable" || pc.signalingState === "have-local-offer") {
                    channel = pc.createDataChannel(label, options);
                    setupChannel(channel);
                }

                // 如果是接收端，监听 ondatachannel
                pc.ondatachannel = (event) => {
                    channel = event.channel;
                    setupChannel(channel);
                };

                console.log("已连接");
            }

        };
        // console.log('channel created', pc.signalingState);
        // 如果是发起端，创建 DataChannel
        function setupChannel(ch: RTCDataChannel) {
            channelRef.current = ch;

            ch.onopen = () => {
                setIsOpen(true);
                console.log(`DataChannel "${ch.label}" 已打开`);
            };

            ch.onclose = () => {
                setIsOpen(false);
                console.log(`DataChannel "${ch.label}" 已关闭`);
            };

            ch.onerror = (err) => {
                console.error("DataChannel 错误:", err);
            };

            ch.onmessage = (event) => {
                onMessage?.(event.data);
            };
        }
        // pc.addEventListener('iceconnectionstatechange', handleStateChange);

        // return () => {
        //     pc.removeEventListener('iceconnectionstatechange', handleStateChange);
        // };

        return () => {
            channelRef.current?.close();
        };
    }, [pc]);

    return { isOpen, sendMessage };
}
